//
//  ContentView.swift
//  swiftUITest
//
//  Created by 傅智鹏 on 2021/5/17.
//

import SwiftUI
var formatter = DateFormatter()

func initUserData() -> [singleToDo]{
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    var output:[singleToDo] = []
    if let dataStored = UserDefaults.standard.object(forKey: "ToDoList") as?
        Data {
        let data = try! decoder.decode([singleToDo].self, from: dataStored)
        for item in data {
            if !item.deleted {
                output.append(singleToDo(title: item.title, duedate: item.duedate, ischecked: item.ischecked, deleted: item.deleted, isFacorite: item.isFacorite, id: item.id))
            }
        }
    }
    return output
}


struct ContentView: View {
    @ObservedObject var userData:ToDo = ToDo(data: initUserData())
    @State var showEditingPage = false
    @State var editingMode = false
    @State var selection:[Int] = []
    @State var showLikeOnly = false
    @State var allSelect = false
    var body: some View {
        ZStack{
            NavigationView{
                ScrollView(.vertical){
                    VStack {
                        ForEach(self.userData.ToDoList){item in
                            if !item.deleted{
                                if !self.showLikeOnly || item.isFacorite{
                                    singleCardView(index: item.id, editingMode:self.$editingMode,selection:self.$selection)
                                        .environmentObject(self.userData)
                                        .padding(.top)
                                        .padding(.horizontal)
                                        .animation(.spring())
                                        .transition(.slide)
                                }
                            }
                        }
                    }
                }.navigationBarTitle("提醒事项")
                .navigationBarItems(trailing:
                                        HStack(spacing:15){
                                            if self.editingMode{
                                                deleteButton(selection: self.$selection, editingMode: self.$editingMode).environmentObject(self.userData)
                                                
                                                LikeButton(selection: self.$selection, editingMode: self.$editingMode).environmentObject(self.userData)
                                                selectAllButton(selection: self.$selection, allSelect: self.$allSelect).environmentObject(self.userData)
                                            }
                                            if !self.editingMode{
                                                showCollection(showLikeOnly: self.$showLikeOnly)
                                            }
                                            EditingButton(editingMode: self.$editingMode,selection: self.$selection,allSelect: self.$allSelect)
                                        }
                )
            }
            HStack{
                Spacer()
                VStack{
                    Spacer()
                    Button(action: {
                        self.showEditingPage = true
                    }, label: {
                        Image(systemName: "plus.circle.fill")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 60, height: 60)
                            .foregroundColor(.blue)
                            .padding(.trailing)
                    })
                    .sheet(isPresented: self.$showEditingPage, content: {
                        EditingPage()
                            .environmentObject(self.userData)
                    })
                }
            }
        }
    }
}

struct EditingButton:View {
    @Binding var editingMode:Bool
    @Binding var selection:[Int]
    @Binding var allSelect:Bool
    var body: some View{
        Button(action: {
            self.editingMode.toggle()//bool反选
            self.selection.removeAll()
            self.allSelect = false
        }, label: {
            Image(systemName: "gear")
                .imageScale(.large)
        })
    }
    
}


struct deleteButton:View {
    @Binding var selection:[Int]
    @EnvironmentObject var UserData:ToDo
    @Binding var editingMode:Bool
    var body: some View{
        Button(action: {
            for i in self.selection{
                self.UserData.delete(id: i)
            }
            self.editingMode = false
        }, label: {
            Image(systemName: "trash")
                .imageScale(.large)
        })
    }
}

struct showCollection :View{
    @Binding var showLikeOnly:Bool
    var body: some View{
        Button(action: {
            self.showLikeOnly.toggle()
        }, label: {
            Image(systemName: self.showLikeOnly ? "star.fill" : "star")
                .imageScale(.large)
                .foregroundColor(.yellow)
        })
    }
}


struct LikeButton:View {
    @EnvironmentObject var UserData:ToDo
    @Binding var selection:[Int]
    @Binding var editingMode:Bool
    var body: some View{
        Image(systemName: "star.lefthalf.fill")
            .imageScale(.large)
            .foregroundColor(.yellow)
            .onTapGesture {
                for i in self.selection{
                    self.UserData.ToDoList[i].isFacorite.toggle()
                }
                self.editingMode = false
            }
    }
}

struct selectAllButton:View {
    @EnvironmentObject var UserData:ToDo
    @Binding var selection:[Int]
    @Binding var allSelect:Bool
    var body: some View{
        Button(action: {
            if !self.allSelect{
                for item in self.UserData.ToDoList {
                    self.selection.append(item.id)
                    print(self.selection)
                }
            }else{
                self.selection.removeAll()
                print(self.selection)
            }
            self.allSelect.toggle()
        }, label: {
            Image(systemName: self.allSelect ? "checkmark.circle.fill" : "checkmark.circle")
                .imageScale(.large)
                .foregroundColor(.blue)
        })
    }
    
}

struct singleCardView:View {
    @EnvironmentObject
    var UserData:ToDo
    var index:Int
    @State var showEditingPage = false
    @Binding var editingMode:Bool
    @Binding var selection:[Int]
    var body: some View{
        HStack {
            Rectangle()
                .frame(width: 6)
                .foregroundColor(Color("Card" + String(self.index % 5)))
            if self.editingMode{
                Button(action: {
                    self.UserData.delete(id: self.index)
                    self.editingMode = false
                }, label: {
                    Image(systemName: "trash")
                        .imageScale(.large)
                        .padding(.leading)
                })
            }
            
            Button(action: {
                if !self.editingMode{
                    self.showEditingPage = true
                }
            }, label: {
                Group {
                    VStack(alignment: .leading, spacing: 6, content: {
                        Text(self.UserData.ToDoList[index].title)
                            .font(.headline)
                            .fontWeight(.heavy)
                            .foregroundColor(.black)
                        Text(formatter.string(from: self.UserData.ToDoList[index].duedate)).foregroundColor(.gray)
                    })
                    .padding(.leading)
                    Spacer()
                }
            })
            .sheet(isPresented: self.$showEditingPage, content: {
                EditingPage(title: self.UserData.ToDoList[self.index].title,
                            duedate: self.UserData.ToDoList[self.index].duedate,
                            isFacorite:self.UserData.ToDoList[self.index].isFacorite,
                            id:self.index)
                    .environmentObject(self.UserData)
            })
            
            if self.UserData.ToDoList[index].isFacorite{
                Image(systemName: "star.fill")
                    .imageScale(.large)
                    .foregroundColor(.yellow)
                    .padding(.trailing,10)
            }
            
            if self.editingMode{
//                Image(systemName: self.UserData.ToDoList[index].ischecked ? "checkmark.square.fill" : "square")
//                    .imageScale(.large)
//                    .padding(.trailing)
//                    .onTapGesture {//点击事件
//                        self.UserData.check(id: self.index)
//                    }
//            }else{
                Image(systemName: self.selection.firstIndex(where: {$0 == self.index}) == nil ? "circle" : "checkmark.circle.fill")
                    .imageScale(.large)
                    .padding(.trailing)
                    .onTapGesture {//点击事件
                        if self.selection.firstIndex(where:{
                            $0 == self.index
                        }) == nil {
                            self.selection.append(self.index)
                        }
                        else{
                            self.selection.remove(at: self.selection.firstIndex(where:{
                                $0 == self.index})!)
                        }
                    }
            }
            
        }
        .frame(height: 80)
        .background(Color.white)
        .cornerRadius(10)
        .shadow(radius: 6, x:0, y: 6)
    }
}


struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView(userData: ToDo(data:[singleToDo(title: "写作业", duedate: Date(), isFacorite: false),
                                         singleToDo(title: "写作业", duedate: Date(), isFacorite: false)
        ]))
    }
}
